<template>
	<div>
		<TBTree
			ref="TBTreeRef"
			:data="projectMenu"
			:activeId="activeProjectMenu.id"
			:defaultExpandedKeys="['1', '1-2']"
			:props="{
				label: 'name'
			}"
			showCheckbox
			@nodeClick="handleNode"
			@nodeExpand="nodeExpand"
			@checkChange="checkChange"
		>
		</TBTree>
		<el-button type="primary" @click="getCheckedKeys">获取选中节点</el-button>
		<el-button type="primary" @click="setCheckedKeys">还原当前用户菜单权限</el-button>
		<el-button type="primary" @click="resetChecked">清空选中</el-button>
	</div>
</template>

<script>
import {ref, reactive, onMounted, computed} from 'vue'
import {getMenuInfos} from "../../api/menu";
import {getToken} from "../../utils/auth";
import {getInfo} from "../../api/user";
import {ElMessage} from "element-plus";
export default {
	name: 'menu',
	setup() {
		const activeProjectMenu = reactive({
			icon: 'el-icon-office-building',
			name: '主页',
			id: '12'
		})
    const ids =[]
    // 选中用户菜单
    const checkIds = (list)=>{
      list.forEach(items=>{
        if (items.children){
          items.children.forEach((i)=>{
            const {id} = i
            ids.push(id)
          })
        }
      })
      TBTreeRef.value.setCheckedKeys(ids)
    }
    onMounted(()=>{
      // 查询所有菜单
      getMenuInfos().then(res=>{
        projectMenu.value = res.data
      }).catch(e=>{ElMessage.error("加载所有菜单异常："+e)})
      //  查询用户菜单
      getInfo(getToken()).then(re=>{
        //  选中用户菜单
        checkIds(re.data.menuList)
      }).catch(e=>{
        ElMessage.error("加载用户菜单异常："+e)
      })

    })
		const projectMenu = ref([
      {
        icon: 'el-icon-office-building',
        name: '主页',
        id: '1',
        children: [
          {
            icon: 'el-icon-office-building',
            name: 'index',
            id: '12',
          },
        ]
      },
		])

		const TBTreeRef = ref(null)
    //设置节点选中
    function setCheckedKeys() {
      // TBTreeRef.value.setCheckedKeys()
      TBTreeRef.value.setCheckedKeys(ids)
    }
		//节点被点击回调
		function handleNode(node) {
			// console.log('点击节点回调--', node)
			activeProjectMenu.icon = node.icon
			activeProjectMenu.name = node.name
			activeProjectMenu.isActive = node.isActive
			activeProjectMenu.id = node.id
		}

		// 节点被展开回调
		function nodeExpand(expanded, node) {
			// console.log('展开节点回调--', { expanded, node })
		}

		// 节点被选中状态变化回调
		function checkChange(node, checked, indeterminate) {
			// console.log(node, checked, indeterminate)
		}

		// 获取选中节点
		function getCheckedKeys() {
			const nodeKeys = TBTreeRef.value.getCheckedKeys()
			console.log('nodeKeys---', nodeKeys)
		}

		// 清空节点
		function resetChecked() {
			TBTreeRef.value.setCheckedKeys([])
		}

		return {
			TBTreeRef,
			activeProjectMenu,
			projectMenu,
			handleNode,
			nodeExpand,
			checkChange,
			getCheckedKeys,
			setCheckedKeys,
			resetChecked
		}
	}
}
</script>
